﻿package com.tools
{
	import flash.display.*;
	
	import flash.events.*;
	
	import com.data.ImageVO;
	
	import flash.text.TextField;
	
	import flash.net.URLRequest;
	
	import com.conf.GalleryConf;
	
	public class ImageLoader extends Sprite
	{
		// conteneur de l'image
		private var _imageContainer : Sprite;
		
		private var _imageInfos		: ImageVO;
		
		// propriétés utiles au suivi du chargement de l'élément
		public var initialized		: Boolean = false;
		public var loaded			: Boolean = false;
		
		// loader de l'élément
		private var _imageLoader	: Loader;
		// LoaderInfo utiliser pour extraire les données du loader
		private var _imageLI		: LoaderInfo;
		
		private var _waitingText	: TextField = new TextField( );
		
		function ImageLoader ( imageVO : ImageVO )
		{
			if ( loaded ) loaded = false;
			initialized = true;
			
			_imageInfos = imageVO;
			
			_imageContainer = new Sprite( );
			
			addChild( _imageContainer );
			
			init();
		}
		
		private function init( ) : void
		{
			var requete : URLRequest = new URLRequest();
			
			requete.url 	= GalleryConf.MEDIA_FOLDER + GalleryConf.IMAGES_FOLDER + _imageInfos.name;
			
			// on charge la skin
			_imageLoader = new Loader( );
			_imageLoader.load( requete );
			_imageLI = _imageLoader.contentLoaderInfo;
			
			_imageLI.addEventListener ( Event.INIT, initLoading );
			_imageLI.addEventListener ( Event.OPEN, beginLoading );
			_imageLI.addEventListener ( ProgressEvent.PROGRESS, loading );
			_imageLI.addEventListener ( Event.COMPLETE, loadingComplete );
			_imageLI.addEventListener ( IOErrorEvent.IO_ERROR, loadingFailed );
		}
		
		/////////////////////////////////////////////////////////////////////////////////////////////////////////
		// METHODES PRIVEES : GESTIONNAIRES DE CHARGEMENT
		/////////////////////////////////////////////////////////////////////////////////////////////////////////
		
		private function beginLoading ( pEvt : Event ):void
		{
			trace ("démarre chargement");
		}
		
		private function loading ( pEvt : ProgressEvent ):void
		{
			_waitingText.text = "chargement...";
			_imageContainer.addChild( _waitingText );
			trace ("chargement en cours");
		}
		
		private function loadingComplete ( pEvt : Event ):void
		{
			trace( "loading COMPLETE" );
			_imageContainer.removeChild( _waitingText );
			
			initialized = false;
			loaded = true;
			
			pEvt.target.content.width 	= ( _imageInfos.width / GalleryConf.THUMB_RATIO );
			pEvt.target.content.height 	= ( _imageInfos.height / GalleryConf.THUMB_RATIO );
			
			_imageContainer.addChild( pEvt.target.content );
			
			dispatchEvent ( new Event( Event.COMPLETE ) );
		}
		
		private function initLoading ( pEvt : Event ):void
		{
			trace ("initialisation du chargement");
		}
		
		private function loadingFailed ( pEvt : IOErrorEvent ):void
		{
			trace ("erreur de chargement ImageLoader : " + pEvt.text + "\n");
		}
	}
}